package com.ipay.core;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import com.ipay.utils.HttpClientUtils;
import com.ipay.utils.StringUtil;

public class Param extends LinkedHashMap<String, String> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 495499677091491001L;

	public static Param create() {
		return new Param();
	}

	public String toXML() throws IOException {
		Document doc = new Document();
		Element xml = new Element("xml");
		doc.setRootElement(xml);

		Iterator<Map.Entry<String, String>> entryKeyIterator = this.entrySet().iterator();
		while (entryKeyIterator.hasNext()) {
			Map.Entry<String, String> e = entryKeyIterator.next();
			String value=e.getValue();
			String key=e.getKey();
			if (StringUtil.isEmpty(key))continue;
			if(StringUtil.isEmpty(value))continue;
			Element item = new Element(key);
			item.addContent(new CDATA(value));
			xml.addContent(item);
		}
		XMLOutputter xmlout = new XMLOutputter();
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		xmlout.output(doc, bo);
		byte[] buf=bo.toByteArray();//获取内存缓冲区中的数据
		String s = new String(buf, StandardCharsets.UTF_8);
		bo.close();
		return s;
	}

	public static void main(String[] args) throws IOException {
		Param param = Param.create();
		param.put("ToUserName", "toUser");
		param.put("FromUserName", "fromUser");
		param.put("CreateTime", "1348831860");
		param.put("MsgType", "text");
		param.put("Content", "this is a test");
		param.put("MsgId", "1234567890123456");
		System.out.println(param.toXML());
		
	}
}
